package com.atguigu.jdbc;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 798133716@qq.com
 * @create 2021-02-26 15:32
 */
public class JDBCDemo {
    @Test
    public void test() throws SQLException {
//        1创建Driver实例
        Driver driver = new com.mysql.jdbc.Driver();
//        2获取连接对象
//            2.1连接地址
        String url = "jdbc:mysql://localhost:3306/myemployees";
//            2.2properties中设置mysql的账号和密码
        Properties p = new Properties();
        p.setProperty("user","root");
        p.setProperty("password","123321");
        Connection connect = driver.connect(url, p);
        System.out.println(connect);
    }
    @Test
    public void test1(){
//        1创建Driver对象
        try {
            Driver driver = new com.mysql.jdbc.Driver();
//        2注册Driver
            DriverManager.registerDriver(driver);
//        3获取连接对象
            //3.1创建properties对象等待读取配置文件
            Properties p = new Properties();
            //3.2加载流
            p.load(this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"));
            String username = p.getProperty("username");
            String pwd = p.getProperty("pwd");
            String url = p.getProperty("url");
            Connection connection = DriverManager.getConnection(url, username, pwd);
            System.out.println(connection);

        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }

    }
    @Test
    public void test2(){
//        一读取配置文件内容
        InputStream is = null;
        Properties p = null;
        try {
            p = new Properties();
            is = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
//        2properties加载流的配置文件
            p.load(is);
//        3读取文件内容
            String username = p.getProperty("username");
            String pwd = p.getProperty("pwd");
            String url = p.getProperty("url");
            String driverClass = p.getProperty("driverClass");
//            二获取连接对象
//            1Driver类进行类加载
            Class.forName(driverClass);
//            2获取连接对象
            Connection connection = DriverManager.getConnection(url, username, pwd);
            System.out.println(connection);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (is!=null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
